<?php
declare (strict_types=1);

namespace app\controller;

use app\model\User as UserModel;
use app\validate\UserValidate;
use think\exception\ValidateException;
use think\facade\Cookie;
use think\facade\Session;
use think\Request;

class Auth {
    protected $middleware = [
        'auth' 	=> ['only' 	=> ['logout'] ],
        'guest' => ['only' 	=> ['create'] ],
    ];
    public function create() {
        return view();
    }

    public function save(Request $request) {
        //halt($request->post());
        try {
            validate([
                'email|邮箱账号' => 'require|email|max:255|token',
                'password|密码' => 'require|min:6'
            ])->batch()->check($request->post());
            $user = UserModel::where('email', $request->post('email'))->find();
            // halt($user->toArray(),$request->post());
            if ($user && $user->password == sha1($request->post('password') . getSalt())) {
                if($user->actived){
                    Cookie::set('user_id', $user->id, 86400 * 30);
                    session('user', $user);
                    return redirect((string)url('User/read', ['id' => $user->id]))->with('success', '欢迎回来~');
                }else{
                    session('user', null);
                    return redirect((string)url('home'))->with('danger', '您的账号还未激活，请到注册邮箱进行点击激活~');
                }

            } else {
                //记录旧表单输入记录
                Session::flash('old', $request->post());
                return redirect((string)url('login.create'))->with('warning', '您的邮箱账号或者密码输入错误~');
            }


        } catch (ValidateException $e) {
            //记录旧表单输入记录
            Session::flash('old', $request->post());
            if (!empty($errors = $e->getError())) {
                session('errors', $errors);
            }
            return redirect((string)url('login.create'));
        }
    }

    public function logout() {
        session('user', null);
        Cookie::delete('user_id');
        return redirect((string)url('login.create'))->with('success', '成功退出登录~');
    }
}
